package org.liubility.server.usersys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.liubility.pojo.exception.LBException;
import org.liubility.security.commons.BCryptPasswordEncoderUtil;
import org.liubility.server.usersys.entity.User;
import org.liubility.server.usersys.mapper.UserMapper;
import org.liubility.server.usersys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: Jdragon
 * @email: 1061917196@qq.com
 * @Date: 2020.09.04 15:49
 * @Description:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    BCryptPasswordEncoderUtil bCryptPasswordEncoderUtil;

    @Override
    public boolean checkLogin(String name, String rawPassword) throws Exception {
        User user = this.getUserByName(name);
        if (user == null) {
            throw new Exception("账号不存在，请重新尝试！");
        } else {
            //加密的密码
            String encodedPassword = user.getPassword();
            //和加密后的密码进行比配
            if (!bCryptPasswordEncoderUtil.matches(rawPassword, encodedPassword)) {
                throw new Exception("密码不正确！");
            } else {
                return true;
            }
        }
    }

    @Override
    public User register(User regUser) throws LBException {
        User user = this.getUserByName(regUser.getUsername());

        if (user != null) {
            throw new LBException("账号名已存在");
        }
        user = new User();
        user.setUsername(regUser.getUsername());
        user.setPassword(bCryptPasswordEncoderUtil.encode(regUser.getPassword()));

        if (user.insert()) {
            return user;
        } else {
            throw new LBException("注册失败");
        }
    }

    @Override
    public User getUserByName(String name) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, name);
        return getOne(lambdaQueryWrapper);
    }
}
